package com.leoman.controller.company;

import com.leoman.core.Constant;
import com.leoman.entity.CompanyUser;
import com.leoman.exception.*;
import com.leoman.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 企业管理后台控制面板
 * Created by 涂奕恒 on 2016/10/20.
 */
@Controller
@RequestMapping(value = "company")
public class CompanyIndexController {

    @Autowired
    private CompanyUserService companyUserService;

    @Autowired
    private PersonalAuthService personalAuthService;

    @Autowired
    private CompanyAuthService companyAuthService;

    @Autowired
    private CompanyUserGainService companyUserGainService;

    @Autowired
    private AppUserService appUserService;

    @RequestMapping(value = "/dashboard")
    public String dashboard(HttpServletRequest request, ModelMap model) {
        // 获取当前登录人信息
        CompanyUser companyUser = (CompanyUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);

        if (null == companyUser) {
            return "redirect:/company/login";
        }

        companyUser = companyUserService.getById(companyUser.getId());
        model.addAttribute("companyUser", companyUser);
        request.getSession().setAttribute(Constant.CURRENT_ADMIN_USER, companyUser);

        // 统计今日支出
        model.addAttribute("todayMoney", companyUserService.statTodayMoney(companyUser) * -1);

        return "company/控制面板";
    }

    @RequestMapping(value = "/info")
    public String info(HttpServletRequest request, ModelMap model) {
        CompanyUser companyUser = (CompanyUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);

        if (null == companyUser) {
            return "redirect:/company/login";
        }

        companyUser = companyUserService.getById(companyUser.getId());
        request.getSession().setAttribute(Constant.CURRENT_ADMIN_USER, companyUser);

        if (companyUser.getType().equals(Constant.CHECK_STATUS_DEFAULT)) {
            return "company/账户类型选择";
        } else {
            if (!companyUser.getCheckStatus().equals(Constant.CHECK_STATUS_SUCCESS)) {
                if (companyUser.getType().equals(Constant.COMPANY_USER_TYPE_PERSONAL)) {
                    model.addAttribute("personalAuth", personalAuthService.findOneByCompanyUserId(companyUser.getId()));
                    return "company/个人广告主认证";
                } else {
                    model.addAttribute("companyAuth", companyAuthService.findOneByCompanyUserId(companyUser.getId()));
                    return "company/企业广告主认证";
                }
            } else {
                if (companyUser.getType().equals(Constant.COMPANY_USER_TYPE_PERSONAL)) {
                    model.addAttribute("personalAuth", personalAuthService.findOneByCompanyUserId(companyUser.getId()));
                    return "company/个人广告主认证详情";
                } else {
                    model.addAttribute("companyAuth", companyAuthService.findOneByCompanyUserId(companyUser.getId()));
                    return "company/企业广告主认证详情";
                }
            }
        }
    }

    @RequestMapping(value = "/index")
    public String index(Integer index) {
        // index 1=个人认证 2=企业认证
        if (null == index || index == 1) {
            return "company/个人广告主认证";
        } else {
            return "company/企业广告主认证";
        }
    }

    @RequestMapping("save")
    @ResponseBody
    public Integer save(HttpServletRequest request,
                        String userName,
                        Integer paperType,
                        String paperNum,
                        String mobile,
                        String email,
                        String address,
                        MultipartRequest multipartRequest) {
        try {
            CompanyUser companyUser = (CompanyUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);

            if (null == companyUser) {
                return -1;
            }

            companyUser = companyUserService.getById(companyUser.getId());
            request.getSession().setAttribute(Constant.CURRENT_ADMIN_USER, companyUser);

            return companyUserService.savePersonalAuthInfo(companyUser, userName, paperType, paperNum, mobile, email, address, multipartRequest);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @RequestMapping("savePlus")
    @ResponseBody
    public Integer savePlus(HttpServletRequest request,
                            String companyName,
                            String licenseNum,
                            String userName,
                            String mobile,
                            MultipartRequest multipartRequest) {
        try {
            CompanyUser companyUser = (CompanyUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);

            if (null == companyUser) {
                return -1;
            }

            companyUser = companyUserService.getById(companyUser.getId());
            request.getSession().setAttribute(Constant.CURRENT_ADMIN_USER, companyUser);

            return companyUserService.saveCompanyAuthInfo(companyUser, companyName, licenseNum, userName, mobile, multipartRequest);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @RequestMapping(value = "/gotoRegister")
    public String toRegister() {
        return "company/注册";
    }

    @RequestMapping(value = "/gotoForgetPwd")
    public String toForgetPwd() {
        return "company/手机找回";
    }

    @RequestMapping(value = "/serviceInfo")
    public String serviceInfo() {
        return "company/服务条款";
    }

    @RequestMapping(value = "/setPassword")
    public String setPassword(ModelMap model, String mobile, String code) {
        model.addAttribute("mobile", mobile);
        model.addAttribute("code", code);
        return "company/密码设置";
    }

    @RequestMapping("register")
    @ResponseBody
    public Integer register(String mobile, String password, String code) {
        try {
            appUserService.iRegister(mobile, password, code, 1);
            return 1;
        } catch (ParamErrorException e) {
            return 0;
        } catch (MobileExistException e) {
            return -1;
        } catch (CodeErrorException e) {
            return -2;
        }
    }

    @RequestMapping("checkCode")
    @ResponseBody
    public Integer checkCode(String mobile, String code, Integer type) {
        try {
            return appUserService.checkCode(mobile, code, type, 1);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @RequestMapping("forgetPwd")
    @ResponseBody
    public Integer forgetPwd(String mobile, String password, String code) {
        try {
            appUserService.iForgetPwd(mobile, password, code, 1);
            return 1;
        } catch (ParamErrorException e) {
            return 0;
        } catch (MobileNotFindException e) {
            return -1;
        } catch (CodeErrorException e) {
            return -2;
        } catch (UserSealStatusException e) {
            return -3;
        }
    }

    @RequestMapping("sendCode")
    @ResponseBody
    public Integer sendCode(String mobile, Integer type) {
        try {
            appUserService.sendCode(mobile, type, 1);
            return 1;
        } catch (ParamErrorException e) {
            return 0;
        } catch (MobileExistException e) {
            return -1;
        } catch (MobileNotFindException e) {
            return -2;
        }
    }

    @RequestMapping(value = "/productMoney")
    @ResponseBody
    public Integer productMoney(HttpServletRequest request, Double money) {
        try {
            // 获取当前登录人信息
            CompanyUser companyUser = (CompanyUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);
            return companyUserGainService.addMoney(companyUser.getId(), money);
        } catch (ParamErrorException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @RequestMapping(value = "/toRecordMoney")
    public String toRecordMoney(ModelMap model, Integer orderNum, Double money) {
        model.addAttribute("orderNum", "SLSP" + orderNum);
        model.addAttribute("money", money);
        return "company/充值";
    }

    @RequestMapping(value = "/callBackMoney")
    public String callBackMoney(HttpServletRequest request) {
        try {
            // 获取回调参数
            Map<String, String> params = new HashMap<>();
            Map requestParams = request.getParameterMap();
            for (Iterator iterator = requestParams.keySet().iterator(); iterator.hasNext(); ) {
                String name = (String) iterator.next();
                System.out.println();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }

            // 判断是否支付成功
            String trade_status = params.get("trade_status"); // 支付状态
            String out_trade_no = params.get("out_trade_no"); // 订单号
            String total_fee = params.get("total_fee"); // 交易金额

            System.out.println("---------trade_status:" + trade_status);
            System.out.println("---------out_trade_no:" + out_trade_no);
            System.out.println("---------total_fee:" + total_fee);

            // 支付成功
            if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {
                // 修改订单状态
                try {
                    companyUserGainService.changeStatus(Integer.parseInt(out_trade_no.replace("SLSP", "")));

                    System.out.println("---------------------修改订单状态成功");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:dashboard";
    }
}
